﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Annotations;

namespace UpdaterForm.CustomTreeView
{
    public class FileNode : ATreeNode
    {

        private FileInfo _file;
        private String _target;

        private AppData _appData
        {
            get { return Settings.Instance.Data.GetByInstallPath(_target); }

        }

        public FileNode(FileInfo file, String Target)
        {
            Children = new List<ATreeNode>();
            _file = file;
            _target = Target;
            Name = file.Name;
        }


        private bool CheckInLogs()
        {
            var updateDate = Root.Name;
            var log = _appData.History.GetLog(updateDate);
            if (log != null)
            {
                var logFiles = log.TransferedFiles;
                if (logFiles.Count > 0)
                    return logFiles.Contains(_file.FullName);
            }

            return true;
        }

        public override void Initialize()
        {
            IsChecked = CheckInLogs();
        }
         
    public override void Apply(bool Custom)
        {
            if (_appData == null)
                return;
           
                if (Custom)
                {
                    if (IsChecked ?? false)
                        TransferFile();
                }
                else
                    TransferFile();
           
        }

        private void TransferFile()
        {
            DirectoryHelper.MoveFile(_target, _file);
            var updateDate = Root.Name;
            var log = _appData.History.GetLog(updateDate);
            if (log != null)
            {
                var logFiles = log.TransferedFiles;
                if (!logFiles.Contains(_file.FullName))
                    logFiles.Add(_file.FullName);
            }

        }
    }
}
